import Vue from 'vue'
import {Api} from '@/api/index.js'
import VueResource from 'vue-resource'
function dictListToMap(arr, key = 'codingCodeId') {
    var map = {}
    arr.map(item => {
        map[item[key]] = item
    })
    return map
}
export default {
    namespaced: true,
    state: () => ({
        areaTree: null,
        areaMap:null,
        areaTreeMap:null
    }),
    mutations: {
        setArea (state, {areaMap, areaTree, areaTreeMap}) {
            state.areaMap = areaMap
            state.areaTree = areaTree
            state.areaTreeMap = areaTreeMap
        }
    },
    getters: {
        areaTreeMap: state => {
            return state.areaTreeMap?state.areaTreeMap:{}
        },
        areaTree: state => {
            return state.areaTree?state.areaTree:[]
        },
        areaMap: state => {
            return state.areaMap?state.areaMap:[]
        }
    },
    actions: {
        async query({ dispatch, commit, state  },{scope,force=false}){
            if (state.areaTree !== null && force===false) return;
            await scope.$http.get(Api.queryDictBycode + '/CHN-100000', {params: {}}).then((res) => {
                var areaList = res.data.data['CHN-100000']
                var areaMap = dictListToMap(areaList)
                var areaTreeMap = {} //处理不带children
                areaList.forEach(item=>{
                    var codingCodeId = item.codingCodeId
                    var parentCodeId = item.parentCoding
                    var obj = undefined
                    if (areaMap[parentCodeId]) {
                        obj = areaMap[parentCodeId];
                        ((obj['children'] instanceof Array)?'':(obj.children=[]))
                    }else{
                        obj = {codingCodeId:parentCodeId,children:[]}
                        areaMap[parentCodeId] = obj
                    }
                    obj.children.push(item)
                    item.value = codingCodeId
                    item.label = item.codingName

                    if (!areaTreeMap[parentCodeId]) {
                        areaTreeMap[parentCodeId] = []
                    }
                    areaTreeMap[parentCodeId].push({
                        value: codingCodeId,
                        label: item.codingName,
                        children: [],
                        loading: false
                    })
                })
                // console.log(areaTree)
                var areaTree = areaMap['0'].children
                commit('setArea', {areaMap, areaTree,areaTreeMap})
            }).catch(e => {
                console.log("数据字典获取失败")
            });
        }
    },
}